//
//  BIDGlobalMethods.m
//  EducationAssistant
//
//  Created by mal on 15/6/2.
//  Copyright (c) 2015年 cnsoft. All rights reserved.
//

#import "BIDGlobalMethods.h"
#import "BIDDataCommunication.h"
#import "BIDDatabaseManager.h"
#import "AppDelegate+StaticMethod.h"
#import "NSDate+Category.h"

@implementation BIDGlobalMethods
/**
 *设置按钮背景图片
 */
+ (void)setImgForBtn:(UIButton*)btn imgNameForNormal:(NSString*)imgNameForNormal imgNameForHighlight:(NSString *)imgNameForHighlight
{
    UIImage *imgForNormal = [UIImage imageNamed:imgNameForNormal];
    imgForNormal = [imgForNormal resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 11, 11) resizingMode:UIImageResizingModeStretch];
    UIImage *imgForHightlight = [UIImage imageNamed:imgNameForHighlight];
    imgForHightlight = [imgForHightlight resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 11, 11) resizingMode:UIImageResizingModeStretch];
    [btn setBackgroundImage:imgForNormal forState:UIControlStateNormal];
    [btn setBackgroundImage:imgForHightlight forState:UIControlStateHighlighted];
}
/**
 *为按钮的某个状态设置背景图片
 */
+ (void)setImgForBtn:(UIButton*)btn imgName:(NSString*)imgName state:(UIControlState)state inset:(UIEdgeInsets)inset
{
    UIImage *img = [UIImage imageNamed:imgName];
    UIImage *stretchImg = [img resizableImageWithCapInsets:inset resizingMode:UIImageResizingModeStretch];
    [btn setBackgroundImage:stretchImg forState:state];
}
/**
 *弹出提示窗口
 */
+ (void)showAlertView:(NSString *)msg buttonTitle:(NSString *)title delegate:(id)delegate tag:(int)iTag
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:msg delegate:delegate cancelButtonTitle:title otherButtonTitles:nil, nil];
    alert.tag = iTag;
    [alert show];
}
/**
 *获取给定文字的高度
 */
+ (NSUInteger)getHeightWithString:(NSString *)strText font:(UIFont *)font constraintSize:(CGSize)constraintSize
{
    NSDictionary *attributeDictionary = @{NSFontAttributeName:font};
    CGSize size = [strText boundingRectWithSize:constraintSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attributeDictionary context:nil].size;
    return ceil(size.height);
}
+ (NSUInteger)getHeightWithAttributeString:(NSAttributedString *)strText constraintSize:(CGSize)constraintsSize
{
    CGSize size = [strText boundingRectWithSize:constraintsSize options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;
    return ceil(size.height);
}
/**
 *获取给定文字的宽度
 */
+ (NSUInteger)getWidthWithString:(NSString *)strText font:(UIFont *)font constraintSize:(CGSize)constraintSize
{
    NSDictionary *attributeDictionary = @{NSFontAttributeName:font};
    CGSize size = [strText boundingRectWithSize:constraintSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attributeDictionary context:nil].size;
    return ceil(size.width);
}

/**
 *过滤html标签
 */
+ (NSString*)filterHTML:(NSString *)srcString
{
    NSScanner *scanner = [[NSScanner alloc] initWithString:srcString];
    while(![scanner isAtEnd])
    {
        NSString *strFilter;
        [scanner scanUpToString:@"<" intoString:nil];
        [scanner scanUpToString:@">" intoString:&strFilter];
        srcString = [srcString stringByReplacingOccurrencesOfString:[[NSString alloc] initWithFormat:@"%@>", strFilter] withString:@""];
    }
    srcString = [srcString stringByReplacingOccurrencesOfString:@"&nbsp;" withString:@""];
    srcString = [srcString stringByReplacingOccurrencesOfString:@"\t" withString:@""];
    srcString = [srcString stringByReplacingOccurrencesOfString:@"\r\n\r\n\r\n" withString:@"\r\n"];
    srcString = [srcString stringByReplacingOccurrencesOfString:@"\r\n\r\n" withString:@"\r\n"];
    return srcString;
}

+ (NSString*)createDirectoryInDocument:(NSString *)directoryName
{
    NSString *strDirectory = @"";
    NSArray *arr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *strDocumentPath = arr[0];
    strDirectory = [strDocumentPath stringByAppendingPathComponent:directoryName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL bExist = [fileManager fileExistsAtPath:strDirectory];
    if(!bExist)
    {
        [fileManager createDirectoryAtPath:strDirectory withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return strDirectory;
}
/**
 *获取document路径
 */
+ (NSString*)getDocumentPath
{
    NSArray *arr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *strDocumentPath = arr[0];
    return strDocumentPath;
}
/**
 *  获取附件本地的存储路径
 *
 *  @return <#return value description#>
 */
+ (NSString*)getAttachmentPath
{
    NSString *strDocumentPath = [BIDGlobalMethods getDocumentPath];
    NSString *strAttachmentPath = [strDocumentPath stringByAppendingPathComponent:@"download/attachment"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager createDirectoryAtPath:strAttachmentPath withIntermediateDirectories:YES attributes:nil error:nil];
    return strAttachmentPath;
}
/**
 *  获取头像的本地存储路径
 *
 *  @return 头像名字传空时，返回存储头像的目录的路径。头像名字不为空时，如果头像图片存在，则返回该头像图片的路径，如果不存在，则返回空
 */
+ (NSString*)getPortraitPath:(NSString *)portraitName
{
    NSString *strDocumentPath = [BIDGlobalMethods getDocumentPath];
    NSString *strPortraitPath = [strDocumentPath stringByAppendingPathComponent:@"portrait"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager createDirectoryAtPath:strPortraitPath withIntermediateDirectories:YES attributes:nil error:nil];
    if(portraitName.length>0)
    {
        strPortraitPath = [strPortraitPath stringByAppendingString:portraitName];
        if([BIDGlobalMethods IsFileExist:strPortraitPath])
        {
            return strPortraitPath;
        }
        else
        {
            return @"";
        }
    }
    return strPortraitPath;
}

/**
 *判断文件是否存在
 */
+ (BOOL)IsFileExist:(NSString *)filePath
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if([fileManager fileExistsAtPath:filePath])
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

/**
 *从全路径中获取不带后缀名的文件名字
 */
+ (NSString*)getFileNameWithoutExtension:(NSString *)fullPath
{
    NSString *strFileName = [fullPath lastPathComponent];
    return [strFileName stringByDeletingPathExtension];
}

/**
 *  转换html格式的文本
 *
 *  @param normalText 带html标签的文本
 *
 *  @return 转换后的文本
 */
+ (NSAttributedString*)getAttributeString:(NSString *)normalText
{
    NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[normalText dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSBackgroundColorAttributeName:[UIColor clearColor] } documentAttributes:nil error:nil];
    return attrStr;
}

/**
 *  正则表达式验证
 *
 *  @param content  需要验证的内容
 *
 *  @param pattern  验证模式
 *
 *  @return 转换后的文本
 */
+ (BOOL)validationContent:(NSString *)content withRegPattern:(NSString *)pattern
{
    BOOL bFlag = YES;
    NSRegularExpression *regExpression = [[NSRegularExpression alloc] initWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];
    NSUInteger matchCount = 0;
    matchCount = [regExpression numberOfMatchesInString:content options:NSMatchingReportProgress range:NSMakeRange(0, content.length)];
    if(matchCount==0)
    {
        bFlag = NO;
    }
    return bFlag;
}
/**
 *  获取随机颜色值
 *
 *  @return <#return value description#>
 */
+ (UIColor*)getRandomColor
{
    CGFloat red = arc4random()%256;
    CGFloat blue = arc4random()%256;
    CGFloat green = arc4random()%256;
    return RGBACOLOR(red, green, blue, 1.f);
}
+ (NSArray*)getMultiColorWithCount:(int)count
{
    NSMutableArray *arr = [NSMutableArray array];
    for(int i=0; i<count; i++)
    {
        CGFloat red = arc4random()%256;
        CGFloat blue = arc4random()%256;
        CGFloat green = arc4random()%256;
        UIColor *color = RGBACOLOR(red, green, blue, 1.f);
        [arr addObject:color];
    }
    return arr;
}
/**
 *  获取当前用户详情
 *
 *  @param requestURL <#requestURL description#>
 *  @param completion <#completion description#>
 */
+ (void)getCurrentUserDetailInfoWithURL:(NSString *)requestURL completion:(void (^)(NSDictionary *))completion
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *strUserName = [userDefaults objectForKey:@"username"];
    NSString *strPost = [[NSString alloc] initWithFormat:@"userName=%@", strUserName];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSMutableDictionary *responseDic = [NSMutableDictionary dictionary];
        int rev = [BIDDataCommunication getDataWithURL:requestURL andPost:strPost toDictionary:responseDic];
        dispatch_async(dispatch_get_main_queue(), ^{
            if(rev==1)
            {
                completion(responseDic);
            }
        });
    });
}
+(NSString *)digitUppercase:(NSString *)money
{
    NSMutableString *moneyStr=[[NSMutableString alloc] initWithString:[NSString stringWithFormat:@"%.2f",[money doubleValue]]];
    NSArray *MyScale=@[@"分", @"角", @"元", @"拾", @"佰", @"仟", @"万", @"拾", @"佰", @"仟", @"亿", @"拾", @"佰", @"仟", @"兆", @"拾", @"佰", @"仟" ];
    NSArray *MyBase=@[@"零", @"壹", @"贰", @"叁", @"肆", @"伍", @"陆", @"柒", @"捌", @"玖"];
    NSMutableString *M=[[NSMutableString alloc] init];
    [moneyStr deleteCharactersInRange:NSMakeRange([moneyStr rangeOfString:@"."].location, 1)];
    for(NSUInteger i=moneyStr.length;i>0;i--)
    {
        NSInteger MyData=[[moneyStr substringWithRange:NSMakeRange(moneyStr.length-i, 1)] integerValue];
        [M appendString:MyBase[MyData]];
        if([[moneyStr substringFromIndex:moneyStr.length-i+1] integerValue]==0&&i!=1&&i!=2)
        {
            if([MyScale[i-1] isEqualToString:@"元"])
            {
            }
            else
            {
                [M appendString:MyScale[i-1]];
            }
            [M appendString:@"元整"];
            break;
        }
        [M appendString:MyScale[i-1]];
    }
    return M;
}
/**
 *  数字转大写一、二、三
 *
 *  @param digit <#digit description#>
 *
 *  @return <#return value description#>
 */
+ (NSString*)digit2Capital:(NSString *)digit
{
    NSDictionary *dic = @{@"0":@"零", @"1":@"一", @"2":@"二", @"3":@"三", @"4":@"四", @"5":@"五", @"6":@"六", @"7":@"七", @"8":@"八", @"9":@"九", @"10":@"十"};
    return dic[digit];
}
/**
 *  <#Description#>
 *
 *  @param actualDate <#actualDate description#>
 *
 *  @return <#return value description#>
 */
+ (NSString*)transDate:(NSString *)actualDate
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [dateFormatter dateFromString:actualDate];
    return [date formattedTime];
}

/**
 把字符串型的日期转换成NSDate

 @param formatter <#formatter description#>
 @param stringDate <#stringDate description#>
 @return <#return value description#>
 */
+ (NSDate *)transToNSDateByFormatter:(NSString *)formatter fromStringDate:(NSString *)stringDate
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:formatter];
    return [dateFormatter dateFromString:stringDate];
}

/**
 验证手机号码的格式是否正确

 @param phoneNumber <#phoneNumber description#>
 @return <#return value description#>
 */
+ (BOOL)isMobilePhoneNumberHaveCorrectFormat:(NSString *)phoneNumber
{
    BOOL bFlag = YES;
    NSRegularExpression *regExpression = [[NSRegularExpression alloc] initWithPattern:@"^1[0-9]\\d{9}$" options:NSRegularExpressionCaseInsensitive error:nil];
    NSUInteger matchCount = 0;
    matchCount = [regExpression numberOfMatchesInString:phoneNumber options:NSMatchingReportProgress range:NSMakeRange(0, phoneNumber.length)];
    if(matchCount==0)
    {
        bFlag = NO;
    }
    return bFlag;
}
/**************************************************************************************************
 *正则匹配
 *
 **/
#pragma 正则匹配手机号
+ (BOOL)checkTelNumber:(NSString *) telNumber
{
    NSString *pattern = @"^1+[3578]+\\d{9}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:telNumber];
    return isMatch;
}


#pragma 正则匹配用户密码6-18位数字和字母组合
+ (BOOL)checkPassword:(NSString *) password
{
    NSString *pattern = @"^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{6,18}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:password];
    return isMatch;
    
}

#pragma 正则匹配用户姓名,20位的中文或英文
+ (BOOL)checkUserName : (NSString *) userName
{
    NSString *pattern = @"^[a-zA-Z\u4E00-\u9FA5]{1,20}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:userName];
    return isMatch;
    
}

#pragma 正则匹配用户身份证号15或18位
+ (BOOL)checkUserIdCard: (NSString *) idCard
{
    NSString *pattern = @"(^[0-9]{15}$)|([0-9]{17}([0-9]|X)$)";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:idCard];
    return isMatch;
}

#pragma 正则匹员工号,12位的数字
+ (BOOL)checkEmployeeNumber : (NSString *) number
{
    NSString *pattern = @"^[0-9]{12}";
    
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:number];
    return isMatch;
    
}

#pragma 正则匹配URL
+ (BOOL)checkURL : (NSString *) url
{
    NSString *pattern = @"^[0-9A-Za-z]{1,50}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:url];
    return isMatch;
}

@end
